<template>
  <div class="center-wrap">
    <div class="flex-xbt">
      <i></i>
      <h2>{{ props.query.title }}</h2>
      <p class="a-link">下载应用说明</p>
    </div>
    <custom-form
      @onClickFormItem="onClickFormItem"
      @onClickUploadSingle="onClickUploadSingle"
      @onClickUploadMultiple="onClickUploadMultiple"
      v-model:customOption="customOption"
      v-model:formItem="formItem"
    ></custom-form>

    <div class="btn-wrap">
      <el-row class="flex-xc" style="margin-top: 50px" v-if="props.query.handlerType!=='edit'">
        <el-button @click="runDemoAPP">DEMO</el-button>
        <el-button @click="$router.back()">返回</el-button>
        <el-button type="primary" @click="runAPP">运行</el-button>
      </el-row>
      <el-row class="flex-xc" style="margin-top: 15px" v-if="props.query.handlerType!=='read'">
        <el-button @click="onSubmit">保存</el-button>
        <!-- <el-button>提交</el-button> -->
        <el-button>重置</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </el-row>
    </div>
  </div>
</template>

<script setup lang="ts">
import CustomForm from '../../components/CustomForm.vue'
import { storeToRefs } from 'pinia'
import useAppDevStore from '@/store/modules/member/app/develop.ts'
import {
  reqSaveTempData,
  reqGetTempDataList,
  reqApplicationRun,
  reqAppCopyDemoRun,
  reqUploadSingle,
  reqUpdateMulti,
} from '@/pages/member/api/flowapp'
import {
  reqSaveTempBody,
  reqSaveTempItem,
} from '@/pages/member/api/types/flowapp'
import { MsgError, MsgSuccess } from '@/utils/utils'
import { onMounted } from 'vue'
let props = defineProps<{
  query: { appId: string; title: string; handlerType: string }
}>()

const {
  formOptionData,
  optionForm,
  formItemKey,
  formItemIndexType,
  customOption,
  formItem,
} = storeToRefs(useAppDevStore())

onMounted(async () => {
  const resp = await reqGetTempDataList(Number(props.query.appId))
  if (resp.code === 0) {
    formItem.value = []
    resp.data.map((item) => {
      formItem.value.push(JSON.parse(item.content))
    })
  }
})

// 点击组件
const onClickFormItem = (key: string) => {
  formItemKey.value = key
  formItem.value
    .filter((item) => item.key === key)
    .map((node) => {
      formOptionData.value.title = node.label
      formOptionData.value.tableName = node.prop
      formOptionData.value.order = node.order!
      formOptionData.value.sort = node.sort!
      formOptionData.value.titleEn = node.placeholder
      formOptionData.value.them = node.col
      if (node.options?.length) {
        optionForm.value = node.options.map((optionsItem) => [
          { label: '名称', value: optionsItem.label },
          { label: '值', value: optionsItem.value },
        ])
      } else {
        optionForm.value = []
        formItemIndexType.value = false
      }
    })
}

// 点击单个文件上传
const onClickUploadSingle = async (key: string, files: any) => {
  let temp_formItem = formItem.value.filter((item) => item.key === key)
  const formData = new FormData()
  formData.append('runId', props.query.runId)
  formData.append('applicationId', props.query.applicationId)
  formData.append('smartFlowId', props.query.smartFlowId || 0)
  formData.append('tableName', temp_formItem[0].prop)
  formData.append('file', files[0])
  let resp = await reqUploadSingle(formData)
  if (resp.code === 0) {
    temp_formItem[0].value += temp_formItem[0].prop + ' 已上传 '
    MsgSuccess('上传成功')
  } else {
    MsgError('上传失败: ' + resp.msg)
  }
}

// 点击文件夹上传
const onClickUploadMultiple = async (key: string, files: any) => {
  let temp_formItem = formItem.value.filter((item) => item.key === key)
  const formData = new FormData()
  formData.append('runId', props.query.runId)
  formData.append('applicationId', props.query.applicationId)
  formData.append('smartFlowId', props.query.smartFlowId || 0)
  formData.append('title', files[0].webkitRelativePath.split('/')[0])
  // formData.append('file', files)
  // formData.append('file', files[0])
  for (let i in files) {
    if (typeof(files[i]) === 'object' && files[i].name) {
      formData.append('file', files[i])
    }
  }
  let resp = await reqUpdateMulti(formData)
  if (resp.code === 0) {
    temp_formItem[0].value += formData.get('title') + ' 已上传\n'
    MsgSuccess('上传成功')
  } else {
    MsgError('上传失败: ' + resp.msg)
  }
}

// 保存
const onSubmit = async () => {
  const saveTempList: reqSaveTempItem[] = []
  formItem.value.map((item) => {
    saveTempList.push({
      title: item.label,
      tableName: item.prop,
      content: JSON.stringify(item),
      path: '',
      style: customOption.value.col,
      enable: 0,
    })
  })
  const reqData: reqSaveTempBody = {
    applicationId: Number(props.query.appId),
    list: saveTempList,
  }
  const resp = await reqSaveTempData(reqData)
  if (resp.code === 0) MsgSuccess('保存成功')
}

const $emit = defineEmits<{
  (e: 'runAPP_Callbask', val: string): any
}>()

// 运行DEMO
const runDemoAPP = async () => {
 const { data, msg } = await reqAppCopyDemoRun({
    runId: Number(props.query.runId),
    applicationId: Number(props.query.applicationId),
    smartFlowId: Number(props.query.smartFlowId) || 0,
  })
  $emit('runAPP_Callbask', data)
  if (data) MsgSuccess('执行成功: ' + data)
  else MsgError('执行失败：' + msg)
}

// 运行
const runAPP = async () => {
  // const appId = Number(props.query.appId)
  let temp_list: any = []
  formItem.value.map((item) => {
    // 类型：1 单文件上传 2 多文件上传 3 图片上传 4 选项 5 文本
    let _type: number = 0
    let _runValue: string = ''
    switch(item.handlerType){
      case 'uploadFile':
        _type = 1
        _runValue = item.value
        break
      case 'uploadFiles':
        _type = 2
        _runValue = item.value
        break
      case 'uploadImg':
        _type = 3
        _runValue = item.value
        break
      case 'radio':
        _type = 4
        _runValue = item.value
        break
      case 'checkbox':
        _type = 4
        _runValue = item.value.join(',')
        break
      case 'input':
        _type = 5
        _runValue = item.value
        break
      case 'textarea':
        _type = 5
        _runValue = item.value.split('\n').join(',')
        break
    }
    temp_list.push({
      type: _type,
      title: item.label,
      tableName: item.prop,
      content: JSON.stringify(item),
      value: _runValue,
      path: '',
      style: customOption.value.col,
      enable: 0,
      sort: item.sort,
    })
  })
  const { data, msg } = await reqApplicationRun({
    runId: Number(props.query.runId),
    applicationId: Number(props.query.applicationId),
    smartFlowId: Number(props.query.smartFlowId) || 0,
    list: temp_list,
  })
  $emit('runAPP_Callbask', data)
  if (data) MsgSuccess('执行成功: ' + data)
  else MsgError('执行失败：' + msg)
}
</script>

<style scoped lang="scss">
.center-wrap {
  width: 1132px;
  padding: 33px 40px;
  margin: 0 16px;
  background-color: #fff;

  h2 {
    margin-bottom: 50px;
    font-size: 24px;
    font-weight: bold;
    color: #021429;
  }
}
</style>
